package Controller;
import Controller.Actions.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FrontController extends HttpServlet {
    private HashMap actions;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String path = request.getRequestURL().toString();

        Action action = findAction(path);
          
        if(action != null)
            action.perform(request, response);
        else
        {
            HttpServletResponse httpResponse=(HttpServletResponse)response;
            httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        return;
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    public String getServletInfo() 
    {
        return "Controller";
    }
    
    public void init() throws ServletException 
    {
        //Creamos los subcontrollers y los metemos al hashmap.
        actions = new HashMap();
        actions.put("query", new QueryAction());
        actions.put("train", new TrainAction());
    }
    
   public Action findAction(String servletPath) 
   {
        int index = servletPath.lastIndexOf('/');
        servletPath = servletPath.substring(index+1, servletPath.length());
        return (Action)actions.get(servletPath);
   }
}